﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;


namespace HitchHikersGuideToTheGalaxy.Models
{
    public class UserInfoRepository : HitchHikersGuideToTheGalaxy.Models.IUserInfoRepository
    {
        GalaxyDataContext db = new GalaxyDataContext();

        #region Default Add, Delete and save actions

        /// <summary>
        /// Add UserInfo
        /// </summary>
        /// <param name="userInfo">UserInfo object</param>
        public void Add(UserInfo userInfo)
        {
            db.UserInfos.InsertOnSubmit(userInfo);
        }

        /// <summary>
        /// Delete UserInfo
        /// </summary>
        /// <param name="userInfo">UserInfo object</param>
        public void Delete(UserInfo userInfo)
        {
            db.UserInfos.DeleteOnSubmit(userInfo);
        }

        /// <summary>
        /// Save to database
        /// </summary>
        public void Save()
        {
            db.SubmitChanges();
        }

        #endregion

        #region Querys

        /// <summary>
        /// Find all users
        /// </summary>
        /// <returns></returns>
        public IQueryable<User> FindAllUsers()
        {
            return (from user in db.UserInfos
                    from zip in db.PostalCodes
                    from role in db.UserRoles
                    where user.ZipCode == zip.ZipCode
                    where user.UserRoleId == role.Id
                    select new User
                    {
                        SSN = user.SSN,
                        FirstName = user.FirstName,
                        LastName = user.LastName
                    }).AsQueryable<User>();

        }

        //public IQueryable<UserInfo> FindAllUserInfos()
        //{
        //    return (from user in db.UserInfos
        //            from zip in db.PostalCodes
        //            from role in db.UserRoles
        //            where user.ZipCode == zip.ZipCode
        //            where user.UserRoleId == role.Id
        //            select new User
        //            {
        //                SSN = user.SSN,
        //                FirstName = user.FirstName,
        //                LastName = user.LastName
        //            }).AsQueryable<UserInfo>();

        //}
        public IQueryable<UserInfo> FindAllUserInfos()
        {
            throw new NotImplementedException();
        }

        public UserInfo GetUserInfo(int id)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// Get one UserInfo record from SSN.
        /// </summary>
        /// <param name="ssn"></param>
        /// <returns></returns>
        public UserInfo GetUserInfo(string username)
        {
            return db.UserInfos.SingleOrDefault(d => d.Username == username);
        }

        #endregion
    }
}
